package service

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/domain"
	"gitee.com/chicken-c/go-learn/webook/internal/repostiory"
	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
)

//go:generate mockgen -destination=./mocks/mock_interactive.go -package=mocks . InterActiveService
type InterActiveService interface {
	IncrReadCnt(ctx context.Context, biz string, bizId int64) error
	Like(ctx *gin.Context, liked bool, biz string, aId int64, uId int64) error
	Collect(ctx *gin.Context, collectd bool, biz string, id int64, cId int64, uId int64) error
	//获取interActive相关
	Get(ctx *gin.Context, biz string, id int64, uId int64) (domain.InterActive, error)
	//批量获取interActive 返回的是map,通过文章ID获取对应interactive
	GetByIds(ctx context.Context, biz string, ids []int64) (map[int64]domain.InterActive, error)
}

type interActiveService struct {
	repo repostiory.InterActiveRepository
}

func (i *interActiveService) GetByIds(ctx context.Context, biz string, ids []int64) (map[int64]domain.InterActive, error) {
	//我们在service在转换为map结构
	intrs, err := i.repo.GetByIds(ctx, biz, ids)
	if err != nil {
		return nil, err
	}

	res := make(map[int64]domain.InterActive, len(intrs))
	for _, intr := range intrs {
		res[intr.BizId] = intr
	}

	return res, nil
}

func NewInterActiceService(repo repostiory.InterActiveRepository) InterActiveService {
	return &interActiveService{
		repo: repo,
	}
}

func (i *interActiveService) Get(ctx *gin.Context, biz string, id int64, uId int64) (domain.InterActive, error) {
	//查询点赞/收藏/阅读数量
	intr, err := i.repo.Get(ctx, biz, id)

	var eg errgroup.Group
	//查询该用户是否点赞
	eg.Go(func() error {
		Liked, err := i.repo.Liked(ctx, biz, id, uId)
		if err != nil {
			return err
		}
		intr.Liked = Liked
		return err
	})

	//查询该用户是否收藏
	eg.Go(func() error {
		Collectd, err := i.repo.Collectd(ctx, biz, id, uId)
		if err != nil {
			return err
		}
		intr.Collectd = Collectd
		return err
	})

	_ = eg.Wait()
	return intr, err
}

func (i *interActiveService) Collect(ctx *gin.Context, collectd bool, biz string, id int64, cId int64, uId int64) error {
	if collectd {
		//收藏
		return i.repo.AddCollectionItem(ctx, biz, id, cId, uId)
	} else {
		//取消收藏
		return i.repo.DeleteCollectionItem(ctx, biz, id, cId, uId)
	}
}

func (i *interActiveService) Like(ctx *gin.Context, liked bool, biz string, aId int64, uId int64) error {
	if liked {
		//点赞
		return i.repo.IncrLike(ctx, biz, aId, uId)
	} else {
		//取消点赞
		return i.repo.DecrLike(ctx, biz, aId, uId)
	}
}

func (i *interActiveService) IncrReadCnt(ctx context.Context, biz string, bizId int64) error {
	return i.repo.IncrReadCnt(ctx, biz, bizId)
}
